
import FileSaver from "file-saver";
import htmlDocx from "html-docx-js/dist/html-docx";
import { message } from 'antd'

function getRequestParams(params) {
    let result = '';
    for (const key in params) {
        if (params.hasOwnProperty(key) && params[key]) {
            result += `${key}=${params[key]}&`;
        }
    }
    return result.slice(0, -1);
}

function downloadFile(url: string, data, name: string = '结存导出') {
    // 创建一个a标签
    const a = document.createElement('a');

    // 为a标签设置href属性
    a.href = `${url}?${getRequestParams(data)}`;

    // 为a标签设置download属性
    a.download = name;

    // 将a标签添加到文档中
    document.body.appendChild(a);

    // 触发a标签的click事件
    a.click();

    // 从文档中移除a标签
    document.body.removeChild(a);
}

function downloadFileWithToken(res, name) {
    const blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' });
    FileSaver.saveAs(blob, name);
}

function exportWord(html: string, name: string = 'example.docx') {
    try {
        let converted = htmlDocx.asBlob(html);
        FileSaver.saveAs(converted, name);
        message.success('导出成功')
    } catch (error) {
        message.error('导出失败')
    }
}

export {
    downloadFile,
    exportWord,
    downloadFileWithToken
}